import * as SignalR from '@microsoft/signalr';
import { notification } from 'ant-design-vue';
import { getToken } from '@/utils/token-util';
import { reactive } from 'vue';
import { throttle } from 'lodash-es';
import { logout } from '@/utils/page-tab-util';

let connection;
let lastUserState = reactive({
  online: false,
  realName: ''
});
function init() {
  // 初始化SignalR对象
  connection = new SignalR.HubConnectionBuilder()
    .configureLogging(SignalR.LogLevel.Information)
    .withUrl(
      `${import.meta.env.VITE_API_URL.replace(
        '/api',
        ''
      )}/hubs/onlineUser?access_token=${getToken()}`
    )
    .withAutomaticReconnect({
      nextRetryDelayInMilliseconds: () => {
        return 1000; // 每5秒重连一次
      }
    })
    .build();
}

// 启动连接
export const onStart = () => {
  try {
    init();
    connection.keepAliveIntervalInMilliseconds = 15 * 1000; // 心跳检测15s
    connection.serverTimeoutInMilliseconds = 30 * 60 * 1000; // 超时时间30m
    // 断开连接
    connection.onclose(async () => {
      console.log('断开连接');
    });
    // 重连中
    connection.onreconnecting(() => {
      notification.open({
        message: '提示',
        description: '服务器已断线...',
        type: 'error',
        placement: 'bottomRight'
      });
    });
    // 重连成功
    connection.onreconnected(() => {
      console.log('重连成功');
    });

    connection.on('OnlineUserList', (data: any) => {
      lastUserState = {
        online: data.online,
        realName: data.realName
      };
      notificationThrottle();
    });
    connection.on('ForceOffline', async (data: any) => {
      console.log('强制下线', data);
      await connection.stop();

      logout();
    });
    connection.start().then(() => {
      console.log('启动连接');
    });
  } catch (err) {
    console.log(err);
    setTimeout(onStart, 10000); //错误重连
  }
};

export function ForceOffline(row) {
  // 强制下线
  //connection.off('ForceOffline');
  connection
    .send('ForceOffline', { connectionId: row.connectionId })
    .catch(function (err: any) {
      console.log(err);
    });
}

// 通知提示节流
const notificationThrottle = throttle(
  function () {
    notification.open({
      message: '提示',
      description: `${
        lastUserState.online
          ? `【${lastUserState.realName}】上线了`
          : `【${lastUserState.realName}】离开了`
      }`,
      type: `${lastUserState.online ? 'info' : 'error'}`,
      placement: 'bottomRight'
    });
  },
  3000,
  {
    leading: true,
    trailing: false
  }
);

export { connection as signalR };
